package com.base.core.mvc.core;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.base.core.context.utils.JwtWrapper;
import com.base.core.head.constants.MdcConstants;
import com.base.core.head.dto.JwtBaseDTO;
import com.gitee.magic.core.utils.StringUtils;
import com.gitee.magic.framework.base.constant.Config;
import com.gitee.magic.framework.base.rest.HttpWrapper;
import com.gitee.magic.framework.head.constants.BaseCode;
import com.gitee.magic.framework.head.exception.BusinessException;

import jakarta.servlet.http.HttpServletRequest;


/**
 * 
 * @author start
 *
 */
@Service
public class LoginManager {

	@Value("${jwt.token.secret:1234}")
	private String secret;
	@Autowired
	private HttpServletRequest request;

	public <R extends JwtBaseDTO>R analysisJwt(Class<R> prototype,Boolean isAllowNull) {
		return analysisJwt(prototype,isAllowNull,null);
	}
	
	/**
	 * 解析token
	 * @param <R>
	 * @param prototype
	 * @param isAllowNull
	 * @param testToken 只在dev、test环境下生效
	 * @return
	 */
	public <R extends JwtBaseDTO>R analysisJwt(Class<R> prototype,Boolean isAllowNull,String testToken) {
		String token = request.getHeader(HttpWrapper.AUTHORIZATION);
        if(StringUtils.isEmpty(token)) {
        	if(isAllowNull) {
        		return null;
        	}
        	if(Config.isSystemFlag()) {
    			throw new BusinessException(BaseCode.CODE_401);
        	}else {
        		if(StringUtils.isEmpty(testToken)) {
        			throw new BusinessException(BaseCode.CODE_401);
        		}
                return getJwt(prototype,testToken);
        	}
        }
        return getJwt(prototype,token);
	}
	
	public <R extends JwtBaseDTO>R getJwt(Class<R> prototype,String token) {
		JwtWrapper wrapper = new JwtWrapper(secret);
        R jwt=wrapper.verifyToken(token, prototype);
        MDC.put(MdcConstants.USERID, jwt.getAccessId());
        return jwt;
	}
	
}
